﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.ClientInfoCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.ClientInfoHandler
{
    /// <summary>
    /// 客户信息新增命令处理
    /// </summary>
    public class ClientInfoCreateCommandHandler : IRequestHandler<ClientInfoCreateCommand,APIResult<object>>
    {
        /// <summary>
        /// 客户基本信息仓储
        /// </summary>
        private readonly IBaseRepository<ClientInfo> clientRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;


        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="clientRepository">客户基本信息仓储</param>
        /// <param name="mapper">映射</param>
        public ClientInfoCreateCommandHandler(IBaseRepository<ClientInfo> clientRepository,IMapper mapper)
        {
            this.clientRepository = clientRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<object>> Handle(ClientInfoCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
         
            var obj = mapper.Map<ClientInfo>(request);
            int r = clientRepository.AddAsync(obj).Result;
            if (r > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = r;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
                result.data = r;
            }
            return Task.FromResult(result);
        }
    }
}
